<?php
namespace app\common\model;

use service\LogService;

class ProductOrder extends Base
{
    /**
     * 供应商是否需要续费（-2=需要购买，-1=需要续费，0=提醒续费，1=正常）
     */
    public static function isRenew($userId = 0)
    {
        if($userId == 0) return ['is_renew' => 1, 'text' => ''];

        $userInfo = User::alias('u')
            ->join('user_section us', 'u.section_id=us.id')
            ->where([['u.section_id', '<>', 2], ['us.cate_id', '=', 2], ['u.id', '=', $userId]])
            ->field('us.expire_time, u.section_id, us.is_out')
            ->find();
        
        if($userInfo['is_out']){
            $expireTime = ProductOrder::where(['user_id' => $userId, 'status' => 2])->order('id DESC')->value('expire_time');
        }else{
            $expireTime = $userInfo['expire_time'];
        }
        
        if(!$userInfo) return ['is_renew' => 1, 'text' => ''];
        if($expireTime == 0) return ['is_renew' => -2, 'text' => '新入驻/产品到期，需要购买产品。'];

        $productInfo = Productorder::where([
                ['section_id', '=', $userInfo['section_id']],
                ['pid', '=', 0],
                ['status', '>', 1],
                ['is_installment', '>', 0],
                ['finish_time', '=', 0],
            ])
            ->limit(1)
            ->order('pay_time DESC')
            ->value('product_info');

        $productInfo = json_decode($productInfo, true);

        $expireTimeText = $expireTime ? date('Y年m月d日', $expireTime + $productInfo['delay'] * 86400) : '';

        if($expireTime <= time() && time() <= $expireTime + $productInfo['delay'] * 86400){
            return ['is_renew' => 0, 'text' => '您所购买的产品该续费了，请于' . $expireTimeText . '前续费'];
        }

        if($expireTime + $productInfo['delay'] * 86400 < time()){
            return ['is_renew' => -1, 'text' => '您所购买的产品逾期未续费，请及时续费。'];
        }

        return ['is_renew' => 1, 'text' => ''];
    }

    /**
     * 是否支付
     */
    public static function isPay($orderNo = '')
    {
        return self::getVal(['order_no' => $orderNo], 'pay_time');
    }

    public function getProductInfoAttr($val)
    {
        return json_decode($val, true);
    }
}